/*!
 @header CircleListViewController.m
 @author 王 文彬
 @version 1.0.0 2013/01/29 Creation
 Copyright (c) 2013年 mypocketbaby. All rights reserved.
 */

#import "CircleListViewController.h"
#import "Helper.h"
#import "Config.h"
#import "CircleFormViewController.h"
#import "CircleMemberListController.h"
#import "JMFBase.h"

//  -业务逻辑细节说明-
//
//  @abstract       CircleListViewController用于列出所有的圈子。在视图将被加载时，会异步发出刷新请求。
//                      同时，每个实例，都在第一次刷新时，才出现菊花，之后不出现（由_viewLoaded变量决定）。

//  @discussion     

//  @notes          


//  -类修改日志-
//  修改人   修改时间   针对版本   修改描述

@interface CircleListViewController ()

@end

@implementation CircleListViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //设置空白处背景颜色
    self.view.backgroundColor = _SYS_COLOR_BACKGROUND;
    self.tableView.backgroundView = nil;
    //标题
    self.title = _L(@"vc_title_030");

 
    //左侧按钮：返回
    UIButton* backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    //右侧按钮：添加
    UIButton* addButton = [Helper buttonWithStyle:ButtonStyleNavigationAdd];
    [addButton addTarget:self action:@selector(addButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:addButton];
    
    
    //这里不处理_dataSource实例化的时机，由异步请求成功的协议方法处理
    //_dataSource = [[NSMutableArray alloc] init];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


// 每次视图将被载入后，异步请求圈子信息，刷新_dataSource。以保证数据的最新
- (void)viewWillAppear:(BOOL)animated
{
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CIRCLE_LIST];
    request.delegate = (id)self;
    
    //第一次装载视图要显示菊花，根据_viewLoaded的值来判断
    if (_viewLoaded == false) {
        [request setHUD:HUDStyleModeTitle withView:self.view];
        request.hudTitle = _L(@"title_loading_01");
        
        //更新_viewLoaded标记的值，使下次界面载入时不再显示菊花
        _viewLoaded = true;
    }

    [request asynchronous];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return _dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        //圈子的图片，加入点击事件
        UIButton* imageButton = [[UIButton alloc] initWithFrame:CGRectMake(8, 5, 28, 28)];
        [imageButton setBackgroundImage:[UIImage imageNamed:@"dynamic_btn_001"] forState:UIControlStateNormal];
        [imageButton addTarget:self action:@selector(imageButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
//        imageButton.userInteractionEnabled = true;
        
        [cell.contentView addSubview:imageButton];
        
        //圈子名字文字
        UILabel* contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(45, 5, 170, 35)];
        contentLabel.font = _SYS_FONT_002;
        contentLabel.textColor = _SYS_COLOR_002;
        contentLabel.lineBreakMode = UILineBreakModeWordWrap;
        contentLabel.numberOfLines = 0;
        contentLabel.textColor = [UIColor blackColor];
        contentLabel.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:contentLabel];
        
        //圈子统计文字
        UILabel* numberLabel = [[UILabel alloc] initWithFrame:CGRectMake(220, 5, 55, 35)];
        numberLabel.font = _SYS_FONT_004;
        numberLabel.textColor = [UIColor orangeColor];
        numberLabel.backgroundColor = [UIColor clearColor];
        numberLabel.textAlignment = UITextAlignmentRight;
        [cell.contentView addSubview:numberLabel];
    }
    
    NSDictionary* circle = _dataSource[indexPath.row];
    UIButton* imageButton = cell.contentView.subviews[0];
    UILabel* contentLabel = cell.contentView.subviews[1];
    UILabel* numberLabel = cell.contentView.subviews[2];
    
    //设置本行的row值给图片，图片点击的时候就可以通过_dataSource的row行获取到Circle对象
    [imageButton setTag:indexPath.row];
    [contentLabel setText:circle[@"name"]];
    [numberLabel setText:[NSString stringWithFormat:@"（ %i ）", [circle[@"memberCount"] intValue]]];
    [numberLabel sizeToFit];
    numberLabel.frame = CGRectMake(cell.bounds.origin.x+cell.bounds.size.width-numberLabel.frame.size.width-50.0f, 5, numberLabel.frame.size.width, 35);
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    
    CircleMemberListController* memberListVC = [[CircleMemberListController alloc] init];
    memberListVC.circle = [_dataSource objectAtIndex:indexPath.row];
    
    [self.navigationController pushViewController:memberListVC animated:true];
}


#pragma mark - 自定义事件

/*!
 @abstract 返回按钮事件
 */
- (void) backButtonEvent
{
    //显示下拉菜单的视图
    NSArray* views = self.navigationController.navigationBar.subviews;
    for (int i = 0; i < views.count; i++) {
        UIView* view = [views objectAtIndex:i];
        if (view.tag == 99) {
            [view setHidden:false];
        }
    }
    
    //pop
    [self.navigationController popViewControllerAnimated:true];
}

/*!
 @abstract 圈子图片点击事件。
 通过获取sender的tag，可以得知被点击的圈子的ID
 */
- (void)imageButtonEvent:(id)sender
{
    CircleFormViewController* circleFormViewController = [[CircleFormViewController alloc] init];
    
    //通过sender.tag，从_dataSource中取到对应的Circle对象
    circleFormViewController.circle = [_dataSource objectAtIndex:((UIButton *)sender).tag];
    
    [self.navigationController pushViewController:circleFormViewController animated:true];
}

/*!
 @abstract 添加圈子按钮点击事件
 */
- (void)addButtonEvent
{
    CircleFormViewController* circleFormVC = [[CircleFormViewController alloc] init];

    UINavigationController* circleFormNC = [[UINavigationController alloc] initWithRootViewController:circleFormVC];
    
    [Helper navigationControllerCommonStyle:circleFormNC];

    [self.navigationController presentModalViewController:circleFormNC animated:true];
}


#pragma mark - JSONRequestDelegate

//
- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];

    if (jmf.status == JMStatusSucceed) {
        //成功的获取了圈子数据后，清除_dataSource的数据。后面会对这个部分重新填充
        //判断一下是否有实例
        if (_dataSource == nil) {
            _dataSource = [[NSMutableArray alloc] init];
        }
        
        [_dataSource removeAllObjects];
        [_dataSource addObjectsFromArray:(NSArray *)jmf.data];
        
        [self.tableView reloadData];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}


- (void)requestFailWithNetworkUnavailabe
{    
    [Helper showAlertWithTitle:@"" andMessage:_L(@"title_networkunavailabe")];
}


@end
